package ops.controller;

import ops.WindowManager;
import ops.i18n.Resources;
import ops.model.Student;
import ops.model.manager.EntityController;
import ops.model.manager.StudentManager;
import ops.util.ViewHelper;
import ops.view.MenuBar;

public class LoginController {

	private StudentManager studentManager;
	
	private long studentCode;
	
	public LoginController() {
		studentManager = EntityController.getInstance().getStudentManager();
	}
	
	public void login(String user, String password) {
		
		try {
			Long studentCode = Long.parseLong(user);
			// it's only a number, prolly student trying to login.			
			studentLogin(studentCode);
		} catch (NumberFormatException e) {
			// not a number, try normal login procedures.
			adminLogin(user, password);
		}
		
	}

	private void adminLogin(String user, String password) {
		Resources resources = Resources.getInstance();

		if (user.equals("admin") && password.equals("admin")) {
			MenuBar menu = WindowManager.getInstance().getApplicationFrame().menuBar();
			
			menu.changePermissionAdmin(true);
			menu.changePermissionCommons(true);
			menu.changePermissionStudent(false);
			
			redirect();
			changeStatus(user);
			
			studentCode = -1;
		} else {
			ViewHelper.showError(resources.getString("login.failed"));
		}
	}

	private void studentLogin(long studentCode) {
		Resources resources = Resources.getInstance();
		
		Student s = studentManager.getObjectByKey(studentCode);
		if (s == null) {
			ViewHelper.showError(resources.getString("login.failed"));
		} else {
			MenuBar menu = WindowManager.getInstance().getApplicationFrame().menuBar();

			menu.changePermissionAdmin(false);
			menu.changePermissionCommons(true);
			menu.changePermissionStudent(true);
			
			redirect();
			changeStatus(String.valueOf(studentCode));
			
			this.studentCode = studentCode;
		}
	}
	
	public void logout() {
		changeStatus("");

		MenuBar menu = WindowManager.getInstance().getApplicationFrame().menuBar();
		
		menu.changePermissionAdmin(false);
		menu.changePermissionCommons(true);
		menu.changePermissionStudent(false);
	}
	
	private void redirect() {
		WindowManager.getInstance().getApplicationFrame().showPanel("login.success");
	}
	
	private void changeStatus(String user) {
		WindowManager.getInstance().getApplicationFrame().statusPanel().changeStatus(user);
	}
	
	public long getStudentCode() {
		return studentCode;
	}
}
